<template>
  <section>
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative small-header ">
        <el-row class="flex">
          <el-col :sm="24" :md="24" :lg="12" :xl="12">
            <span class="title-icon margin-right">操作指令信息</span>

            <!-- <div> -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downOperationInstructionData"
            >
              导出操作指令信息
            </el-button>
            <el-button
              v-if="isEdit"
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              @click="uploadDialog = true"
            >
              导入操作指令信息
            </el-button>
            <el-button
              v-if="isEdit"
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              @click="uploadTagDialog = true"
            >
              上传标签文件
            </el-button>
            <el-button
              v-if="isEdit"
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="addReturnBatchIndex"
            >
              新增操作批次
            </el-button>
          </el-col>
          <el-col
            :sm="23"
            :md="23"
            :lg="11"
            :xl="11"
            class="flex text-blue align-center justify-between"
          >
            <div>
              <span class="margin-lr">
                总产品预报数量：{{ totalAmount[0] }}
              </span>
              <span class="margin-lr"> 总换标数量 ：{{ totalAmount[1] }} </span>
              <span class="margin-lr"> 总清点数量：{{ totalAmount[2] }} </span>
              <span class="margin-lr"> 总检修数量：{{ totalAmount[3] }} </span>
              <span class="margin-lr"> 总销毁数量：{{ totalAmount[4] }} </span>
            </div>
            <el-button
              v-if="isEdit"
              type="success"
              size="mini"
              @click="changeCargoInfo"
            >
              保存
            </el-button>
          </el-col>
          <el-col
            :sm="1"
            :md="1"
            :lg="1"
            :xl="1"
            class="text-right flex align-center"
            style="justify-content: flex-end;"
          >
            <i
              :class="{
                'el-icon-arrow-down': show,
                'el-icon-arrow-up': !show
              }"
              class="text-lg pointer margin-left"
              @click="show = !show"
            />
          </el-col>
        </el-row>

        <!-- </div> -->
      </div>
      <div v-show="show">
        <hot-table
          ref="hotTable"
          :settings="hotSettings"
          :data="operationInstructionData"
        />
      </div>

      <div class="text-red margin-top-sm ">
        <span class="margin-right">
          如需换标，请提供PDF格式标签
        </span>
      </div>
    </el-card>

    <ImportPop
      :upload-dialog.sync="uploadDialog"
      :dialog-title="`批量导入信息`"
      :action-url="`/abroad/waybills/uploadOperationInstruct`"
      :file-name="`uploadInstructTemp`"
      :waybill-id="waybillId"
      @uploadCb="uploadCargoInfo"
    />
    <ImportPop
      :upload-dialog.sync="uploadTagDialog"
      :dialog-title="`上传标签文件`"
      :upload-tips="uploadTips"
      :action-url="`/abroad/waybills/uploadAbroadWaybillLabelFile`"
      :file-name="`uploadLabelFile`"
      :waybill-id="waybillId"
      @uploadCb="uploadCargoInfo"
    />
  </section>
</template>

<script>
import ImportPop from '@/components/ImportPop'
import { HotTable } from '@handsontable/vue'
import { compileStr } from '@/utils'
// import Handsontable from 'handsontable'
import 'handsontable/languages/zh-CN'
import globalData from '@/utils/config'
import {
  downLoadInstruction,
  updateOperationInstruct,
  queryReturnBatchCountById,
  deleteOperationInstruct,
  saveReturnBatch
} from '@/api/abroadWaybill'
export default {
  name: 'OrderToOrderToOverseasWarehouseShipping',
  components: {
    HotTable,
    ImportPop
  },
  props: {
    operationInstructionData: {
      type: Array,
      default: function() {
        return [{}]
      }
    },
    oldOperationInstructionData: {
      type: Array,
      default: function() {
        return [{}]
      }
    },
    returnCountry: {
      type: Number,
      default: 0
    },
    actionUrl: {
      type: String,
      default: ''
    },
    waybillId: [String, Number],

    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      uploadTips: '',
      tipsList: [
        'US Letter 1页30个标签',
        '一页24个，37毫米*70毫米',
        '一页27个标签，29.6毫米*63.5毫米'
      ],
      uploadDialog: false,
      uploadTagDialog: false,
      returnBatchIndex: 0,
      autoHeight: 'auto',
      waybillGoodsInfos: [{ isMixedLoad: 1 }, {}, {}, {}, {}]
    }
  },
  computed: {
    totalAmount() {
      let totalNums = 0
      let changeNums = 0
      let checkNums = 0
      let repairNums = 0
      let destoryNums = 0

      for (const i of this.operationInstructionData) {
        if (i.totalNum) {
          totalNums += parseInt(i.totalNum)
        }
        if (i.changeNum) {
          changeNums += parseInt(i.changeNum)
        }
        if (i.checkNum) {
          checkNums += parseInt(i.checkNum)
        }
        if (i.repairNum) {
          repairNums += parseInt(i.repairNum)
        }
        if (i.destoryNum) {
          destoryNums += parseInt(i.destoryNum)
        }
      }

      return [totalNums, changeNums, checkNums, repairNums, destoryNums]
    },
    hotSettings() {
      return {
        rowHeaders: true, // 行表头
        stretchH: 'all', // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: [
          '<i style="color:red;margin-right:3px">*</i>旧FNSKU<br>(old)',
          '退货编号',
          '<i style="color:red;margin-right:3px">*</i>Quantity of Product forecast<br>产品预报个数',
          'NEW FNSKU#<br>新FNSKU',
          'Quantity of relabeling<br>换标数量',
          'Count the quantity<br>清点数量',
          'Quantity of repair<br>检修数量',
          'Quantity of destruction<br>销毁数量',
          'FBA warehouse address code FBA<br>仓库地址代码',
          '<i style="color:red;margin-right:3px">*</i>Single FNSKU or Mixed packed<br>单独装箱或混装',
          'Operational requirements<br>操作要求',
          'Operation description<br>操作说明',
          '操作'
        ],
        width: '100%',
        height: this.autoHeight,
        columns: [
          {
            data: 'oldSku', // 指定所指列
            width: 100,
            type: 'text' // 类型
          },
          {
            data: 'returnNo',
            width: 100,
            readOnly: true,
            type: 'text'
          },
          {
            data: 'totalNum',
            width: 100,
            type: 'text'
          },
          {
            data: 'newSku',
            width: 100,
            type: 'text'
          },
          {
            data: 'changeNum',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'checkNum',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'repairNum',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'destoryNum',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'fbaCode',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'isMixedLoad',
            width: 100,
            type: 'dropdown',
            source: ['单独装箱', '混装']
          },
          {
            data: 'operatorAsk',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            data: 'operatorIns',
            width: 100,
            type: 'numeric',
            numericFormat: {
              pattern: '0'
            }
          },
          {
            readOnly: true,
            // width: 100,
            renderer: this.coverRenderer
          }
        ],
        tableClassName: ['first-class-name', 'second-class-name'],
        language: 'zh-CN',
        contextMenu: ['row_above', 'row_below', 'remove_row', 'alignment'], // 开启右键菜单
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.operationInstructionData.length === 1) {
            this.operationInstructionData.push({
              waybillId: this.waybillId,
              id: ''
            })
          }
        },
        afterCreateRow: (index, amount, source) => {
          console.log('index :>> ', index)
          this.operationInstructionData[index].waybillId = this.waybillId
          this.operationInstructionData[index].id = ''
        }
      }
    }
  },
  watch: {
    returnCountry(nVal, oVal) {
      switch (nVal) {
        case 329:
        case 332:
          this.uploadTips = this.tipsList[0]
          break
        case 331:
        case 333:
        case 334:
        case 336:
        case 330:
          this.uploadTips = this.tipsList[1]
          break
        case 335:
          this.uploadTips = this.tipsList[2]
          break
      }
    },
    operationInstructionData(newValue, oldValue) {
      console.log('newValue :>> ', newValue)

      for (const i of this.operationInstructionData) {
        if (i.isMixedLoad === 0) {
          i.isMixedLoad = '单独装箱'
        } else if (i.isMixedLoad === 1) {
          i.isMixedLoad = '混装'
        }
      }
      if (newValue.length === 0) {
        this.$emit('update:operationInstructionData', [
          { waybillId: this.waybillId, id: '' }
        ])
      }

      const length = newValue.length
      if (length < 6) {
        this.autoHeight = '250px'
      } else {
        this.autoHeight = 'auto'
      }
    }
  },
  methods: {
    closeDialog() {
      this.uploadDialog = false
    },
    async downOperationInstructionData() {
      this.$store.dispatch('app/toggleDialog', true)
      const { fileName } = await downLoadInstruction({
        id: this.waybillId
      })
      if (fileName) {
        window.open(globalData.fileUrl + fileName)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    uploadCargoInfo(file) {
      console.log('uploadCargoInfo', file)
      this.$emit('getOperation')
    },

    changeCargoInfo() {
      for (const i of this.$refs.hotTable.data) {
        if (!i.oldSku || !i.totalNum || !i.isMixedLoad) {
          this.$message.error('请填写必填信息')
          return
        }
      }
      // TODO 保存操作
      this.saveInfo()
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)

      // 标记已删除数据
      const arr = []
      for (const i of this.oldOperationInstructionData) {
        const target = this.operationInstructionData.find(x => x.id === i.id)
        console.log('target :>> ', target)
        if (!target) {
          i.isDel = true
          arr.push(i)
        }
      }
      const params = [...this.operationInstructionData, ...arr]

      // TODO
      for (const i of params) {
        if (!i.waybillId) {
          i.waybillId = this.waybillId
        }
        if (i.isMixedLoad === '单独装箱') {
          i.isMixedLoad = 0
        } else if (i.isMixedLoad === '混装') {
          i.isMixedLoad = 1
        }
      }

      const { code, message } = await updateOperationInstruct({
        abroadOperationInstructs: params
      })

      if (code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
      } else {
        this.$message.error(message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    async addReturnBatchIndex() {
      this.$store.dispatch('app/toggleDialog', true)
      const { code, data } = await queryReturnBatchCountById({
        id: this.waybillId
      })

      if (code === 200) {
        this.returnBatchIndex = parseInt(data)
        this.$confirm(
          `确定要新增操作批次${data}吗？点击确定将为您创建一个新的运单。`,
          '新增操作批次',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            this.saveReturn()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      }

      this.$store.dispatch('app/toggleDialog', false)
    },
    async saveReturn() {
      this.$store.dispatch('app/toggleDialog', true)
      const { code, data } = await saveReturnBatch({
        id: this.waybillId,
        returnBatchIndex: this.returnBatchIndex
      })

      if (code === 200) {
        const routeUrl = this.$router.resolve({
          path: '/abroadWaybill/abroadWaybillEdit',
          query: { id: compileStr(data.toString()) }
        })
        window.open(routeUrl.href, '_blank')
      }

      this.$store.dispatch('app/toggleDialog', false)
    },
    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = `` // 清空单元格子集

      const btnDel = document.createElement('i')

      btnDel.setAttribute(
        'class',
        'el-icon-remove-outline margin-right-sm text-red pointer'
      )
      btnDel.setAttribute('v-loading.fullscreen.lock', 'fullscreenLoading')
      btnDel.onclick = params => {
        // console.log("this :>> ", this);
        this.onDel(row)
      }

      td.appendChild(btnDel) // 添加按钮到单元格

      return td
    },
    // 删除
    async onDel(row) {
      console.log('row :>> ', row)
      this.loading = true
      if (this.operationInstructionData[row].id) {
        const data = await deleteOperationInstruct({
          id: this.operationInstructionData[row].id
        })
        if (data.code === 200) {
          this.$message.success('删除成功！')
          this.operationInstructionData.splice(row, 1)
        } else {
          this.$message.error(data.message || '删除失败！')
        }
      } else {
        this.operationInstructionData.splice(row, 1)
      }

      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}

.header-save-btn {
  top: 0%;
}
</style>
